/* eslint-disable react/no-unused-state */
/* eslint-disable react/no-direct-mutation-state */
import React, { Component } from 'react';
import cx from 'classnames';

import LoadingIcon from './Loading';
import AjaxModel from './model';

import S from './index.m.less';

class GoodsWall extends Component {
    static defaultProps = {
        endTips: false, // 到底提示
        isHandleError: false, // 是否自己处理code != 0 的情况
    };

    _updated = true;

    constructor(props) {
        super(props);
        Object.assign(this, AjaxModel);
        this.state = {
            ajaxParam: this.props.ajaxParam || {},
            templates: this.props.templates,
            initLoading: this.props.initLoading,
            ajaxUrl: this.props.ajaxUrl,
            ajaxType: this.props.ajaxType || 'get',
            ajaxDataType: this.props.ajaxDataType || 'json',
            firstScreenData: this.props.firstScreenData,
            bottomHeight: this.props.bottomHeight || 2000,
            preHandleData: this.props.preHandleData, // 数据处理
            isEnd: false, // 结束加载
            items: [],
            callBack: this.props.callBack,
            key: $('#J_Page .curPage').data('page'),
            time: Date.now(),
        };
        if (process.env.NODE_ENV !== 'production' && process.env.LOCAL) {
            const msg = 'GoodsWall组件当前版本已废弃，请使用v2版本';
            console.error(msg);
            console.warn(msg);
        }
    }

    componentDidMount() {
        // 页面渲染后
        this.catch = this.catch || [];
        this.catch.push('1');
        this.initLoaderTimer();
    }

    UNSAFE_componentWillReceiveProps(props) {
        this.state.ajaxParam = props.ajaxParam;
    }

    componentDidUpdate() {
        // 在组件的更新已经同步到 DOM 中之后立刻被调用。该方法不会在初始化渲染的时候调用
        if (!this._isLoading) {
            this._updated = true;
        }

        WPT.initLazy();
        if (this.state.callBack) {
            this.state.callBack();
            this.state.callBack = null;
        }
    }

    componentWillUnmount() {
        this.destroy();
    }

    ajaxSuccBack(res = {}) {
        if (this.state.preHandleData) {
            // 接口正确响应 或者 GoosWall组件要自己处理错误的时候，才调用preHandleData
            if (res.code == 0 || this.props.isHandleError) {
                res = this.state.preHandleData.call(this, res) || {};
            }
        }

        let start = res.start;
        let page = res.page;
        let isEnd = res.isEnd;
        let serverData = res.serverData;

        let items = res.items;
        if (!items && res.data) {
            items = res.data.items;
            start = res.data.start;
            page = res.data.page;
            isEnd = res.data.isEnd;
            serverData = res.data.serverData;
        }
        if (!this.state.items) {
            this.state.items = [];
        }
        this.state.items = this.state.items.concat(items || []);
        // start page 会在下次请求的的时候传递给后端，serverData对象会在展开后传递给后端
        this.setState({
            start,
            page,
            serverData,
            isEnd,
            nowTime: res.nowTime,
        });
        this.state.result = {
            isEnd,
            start,
            serverData,
            page,
            items: this.state.items,
        };
    }

    ref = (ref) => {
        this.wall = ref;
    };

    renderEndTips() {
        const { endTips } = this.props;
        const { state } = this;
        if (state.isEnd && state.items.length > 0) {
            if (typeof endTips === 'boolean') {
                return endTips ? <div className="goodsWallEndTips" /> : null;
            }
            return endTips;
        }
        return null;
    }

    render() {
        const state = this.state;
        const Templates = state.templates;
        const { inverse, loadingText, className } = this.props;
        // eslint-disable-next-line no-use-before-define
        let InitLoading = Loading;
        if (typeof state.initLoading === 'function') {
            InitLoading = state.initLoading;
        }
        const isNoData = state.isEnd && state.items.length === 0;

        const style = isNoData && this.props.noData ? { position: 'relative', minHeight: '8rem' } : null;

        return (
            <div className={cx('wall-container clearfix', className)} style={style} ref={this.ref}>
                <div className="wall-col clearfix">
                    <Templates
                        items={state.items}
                        parent={this.props.parent}
                        page={state.page}
                        nowTime={state.nowTime}
                        isEnd={state.isEnd}
                        isNoData={isNoData}
                    />
                </div>
                {state.initLoading && !state.isEnd && !state.page && <InitLoading />}
                {!state.isEnd && state.page && (
                    <Loading loadingClass={this.props.loadingClass} inverse={inverse} loadingText={loadingText} />
                )}
                {!!isNoData && this.props.noData && <NoData noData={this.props.noData} />}
                {this.renderEndTips()}
            </div>
        );
    }
}

export class NoData extends Component {
    render() {
        const { noData } = this.props;
        return (
            <div className={S.noData}>
                <div className={S.noDataCon}>
                    <LazyImage src={noData.img} autoHeight className={S.bgImg} />

                    {noData.title && (
                        <div className={S.dataTip} style={{ color: noData.title.color || '#a3a3a3' }}>
                            {noData.title.name || noData.title || ''}
                        </div>
                    )}
                </div>
            </div>
        );
    }
}

export class Loading extends Component {
    render() {
        const { inverse = false, loadingClass, loadingText } = this.props;
        const text = loadingText || (loadingClass ? '正在加载中...' : '加载中...');
        return (
            <div className={`wall_loading ${loadingClass}`} style={{ ...(inverse && { color: '#ddd' }) }}>
                {!loadingClass && <LoadingIcon width="0.4rem" height="0.4rem" theme={inverse ? 'white' : 'red'} />}
                {text}
            </div>
        );
    }
}

export default AjaxModel(GoodsWall);
